/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package casino;

import java.util.ArrayList;
import java.util.Set;

/**
 * Player that uses the cancellation betting strategy.
 * 
 * @author  amaghfur
 * @since   1.0
 */
public class PlayerCancellation extends Player {
    
    private ArrayList<Rational> sequence = new ArrayList<>();
    private Outcome outcome = OutcomeFactory.getOutcomeFactory().createOutcome("Black", 1);
    private Rational firstBet = new Rational(10);
    
    public PlayerCancellation(Table tableToPlay) {
        super(tableToPlay);
        resetSequence();
    }
    
    @Override
    public void placeBets() {
        int sequenceSize = sequence.size();
        
        if (sequenceSize <= 1) {    // if end of sequence, reset
            reset();
            sequenceSize = sequence.size();
        }
                            
        Rational betMultiplier = sequence.get(0).plus(sequence.get(sequenceSize-1));
        Rational betAmount = firstBet.times(betMultiplier);
        
        if (betAmount.greaterThan(getStake())) { // end session if not enough money to follow betting strategy
            setRounds(0);
            return;
        }

        Bet blackBet = new Bet(betAmount, outcome);
        
        try {
            getTable().placeBet(blackBet);
            setStake(getStake().minus(betAmount));
        }
        catch (InvalidBetException e) {
            System.err.println("Caught InvalidBetException: " + e.getMessage());
        }  
    }

    @Override
    public void win(Bet bet) {
        setStake(getStake().plus(bet.winAmount()));
        sequence.remove(0); // remove first in sequence
        int sequenceSize = sequence.size();
        sequence.remove(sequenceSize-1); // remove last in sequence
        System.out.println(bet.toString() + " -> won " + bet.winAmount().toString());
    }

    @Override
    public void lose(Bet bet) {
        Rational betAmountLost = bet.getAmountBet();
        sequence.add(betAmountLost.divides(firstBet));
        System.out.println(bet.toString() + " -> lost " + bet.loseAmount().toString());
    }

    @Override
    public void winners(Set<Outcome> outcomes) {
    }
    
    @Override
    public void reset() {
        resetSequence();
    }
    
    private void resetSequence() {
        sequence.clear();
        sequence.add(new Rational(1));
        sequence.add(new Rational(2));
        sequence.add(new Rational(3));
        sequence.add(new Rational(4));
        sequence.add(new Rational(5));
        sequence.add(new Rational(6));
    }
    
}
